{% extends 'base/base_site.html' %}
{% block css %}
    {{ block.super }}
{% endblock %}
{% block content %}
    <div class="ibox-title" style="background-color:#E8FFF5">
        <h5>资产列表</h5>
    </div>
    <div class="ibox-content">
        <div id="DataTables_Table_0_wrapper" class="dataTables_wrapper form-inline">
            <div class="row">
                <div class="col-sm-10">
                    <div class="dataTables_length" id="DataTables_Table_0_length" style="margin-bottom:15px;">
                        {{ request.perms.List }}
                        <a class="btn btn-sm btn-success btn-add" data-toggle="modal" data-target="#addInfoModal"><i
                                class="fa fa-plus"></i> 添加主机</a>
                        <input type="text" placeholder="搜索: 服务、名称、IP等" id="search" class="form-control input-sm">

                    </div>
                </div>
                <div class="col-sm-2">
                    <a class="btn btn-sm btn-default btn-flush">批量刷新</a>
                </div>
            </div>
            <table class="table table-striped table-bordered table-hover dataTables-example dataTable dtr-inline"
                   id="DataTables_Table_0" role="grid" aria-describedby="DataTables_Table_0_info">
                <thead>
                <tr role="row">
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1" aria-sort="ascending">序号
                    </th>
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1">IP</th>
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1">主机名称</th>
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1">项目名称</th>
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1">IDC机房</th>
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1">服务名称</th>
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1">运行状态</th>
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1">创建者</th>
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1">创建时间</th>
                    <th tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1">操作</th>

                </tr>
                </thead>
                <tbody id="content">
                {% include 'cmdb/server_table.html' %}
                </tbody>
            </table>

            {% include 'common/paginator.html' %}
        </div>
    </div>
    {% include 'cmdb/server_modal.html' %}
{% endblock %}
{% block javascripts %}
    {{ block.super }}
{#    <script src="/static/js/plugins/chosen/chosen.jquery.js" type="text/javascript"></script>#}
    {#    <script src="/static/js/plugins/iCheck/icheck.min.js"></script>#}


    <script type="text/javascript">
        function resetChosen() {
            var config = {
                '.chosen-select': {
                    width: "100%"
                },
                '.chosen-select-deselect': {
                    allow_single_deselect: true
                },
                '.chosen-select-no-single': {
                    disable_search_threshold: 10
                },
                '.chosen-select-no-results': {
                    no_results_text: 'Oops, nothing found!'
                },
                '.chosen-select-width': {
                    width: "100%"
                },

            }
            for (var selector in config) {
                $(selector).chosen(config[selector]);
            }
            $('#groups').trigger("chosen:updated");
            $('#edit_groups').trigger("chosen:updated");
        }

        Array.prototype.contains = function (needle) {
            for (i in this) {
                if (this[i] == needle) return true;
            }
            return false;
        }
    </script>

    <script type="text/javascript">

        $('.btn-add').on('click', function () {

            var groups = {{groups |safe}};
            reset();
            $('#groups').empty();
            $.each(groups, function (key, value) {
                var obj = document.getElementById("groups");
                var op = new Option(value[1], value[0])
                obj.add(op);
            });
            resetChosen();
        });

        /**
         * 编辑表单
         * **/

        $('.btn-edit').on('click', function (event) {

            var groups = {{ groups | safe}};
            var idcs ={{ idcs | safe}};
            var apps =
            {{ apps | safe }}
            var users =
            {{ users | safe }}


            var btn = $(event.target);
            var row = btn.data('row').split('|');

            $('#server_id').val(row[0]);
            {#            $('#project_name').val(row[1]);#}
            {#            $('#service_name').val(row[2]);#}
            $('#in_ip').val(row[3]);
            $('#ex_ip').val(row[4]);

            $('#edit_idc').empty();
            $('#edit_groups').empty();
            $('#edit_app').empty();
            $('#edit_system_user').empty();

            var idc = row[6];
            var app = row[7];
            var user = row[8];
            $('#edit_system_user').append("<option value=''>----------</option>");
            jQuery.each(users, function (key, value) {
                var t = jQuery("<option value=" + value[0] + ">" + value[1] + "（" + value[2] + "）" + "</option>");
                if (value[0] == user) {
                    t.attr("selected", "selected");
                }
                $('#edit_system_user').append(t);
            });

            $('#edit_idc').append("<option value=''>----------</option>");
            jQuery.each(idcs, function (key, value) {
                var t = jQuery("<option value=" + value[0] + ">" + value[1] + "</option>");
                if (value[0] == idc) {
                    t.attr("selected", "selected");
                }
                $('#edit_idc').append(t);
            });

            $('#edit_app').append("<option value=''>----------</option>");
            jQuery.each(apps, function (key, value) {
                var t = jQuery("<option value=" + value[0] + ">" + value[1] + "（" + value[2] + "）" + "</option>");
                if (value[0] == app) {
                    t.attr("selected", "selected");
                }
                $('#edit_app').append(t);
            });


            row_group = row[5].split(',');
            if (groups != "") {
                $.each(groups, function (key, value) {
                    var obj = document.getElementById("edit_groups");
                    var op = new Option(value[1], value[0])
                    if (row_group.contains(value[1])) {
                        op.selected = true;
                    }
                    obj.add(op);
                });
            } else if (groups == "") {

                $.each(groups, function (key, value) {
                    var obj = document.getElementById("edit_groups");
                    var op = new Option(value[1], value[0])
                    obj.add(op);
                });
            }
            resetChosen();
        });

        $('.bt-webssh').click(function () {
            var id = $(this).parent().parent().attr('id');
            $.ajax({
                url: "/cmdb/server_webssh/",
                type: 'POST',
                data: {'id': id},
                success: function (ret) {

                    var obj = JSON.parse(ret);
                    var ip = obj.ip;
                    var username = obj.username;
                    var password = obj.password;

                    $.ajax({
                        url: "http://192.168.201.52:8088/console/login?rnd=" + Math.random(),
                        method: "POST",
                        data: {
                            "vm_addr": ip,
                            "user_name": username,
                            "user_pwd": password
                        },
                        dataType: "jsonp",
                        jsonp: 'callback',
                        jsonpCallback: "callback",
                        cache: false,
                        contentType: "application/json;utf-8", /*设置返回类型*/
                        async: false
                    }).done(function (data) {
                        var json = (data);
                        if (json.ok) {
                            {#                            location.href = "http://192.168.201.52:8088" + json.data;#}
                            window.open("http://192.168.201.52:8088" + json.data, "_blank ");
                        } else {
                            alert("登陆失败，请确认您的登陆信息。");
                        }
                    }).fail(function () {
                        alert("未知失败，请联系管理员。");
                    });
                }
            });
        });

         /**
         * 刷新主机信息
         * **/

        $('.btn-flush').on('click', function () {
            var url = "/cmdb/flushAllHosts/"
            $.get(url, function (msg) {
                ajax_callback(msg);
            });
        });

    </script>

    <script>
        /*
        *主机基本信息提示
        */
        $("table tbody tr td a[name='host_name']").each(function () {
            var content = $(this).next().val().split('&');//获取隐藏的主机基本信息内容
            console.log($(this))
            var arr = new Array();
            arr.push("<div><span>系统版本</span>&nbsp&nbsp&nbsp&nbsp" + "<span style='float:right'>" + content[0] + "</span></div>")
            arr.push("<div><span>系统内核</span>&nbsp&nbsp&nbsp&nbsp" + "<span style='float:right'>" + content[1] + "</span></div>")
            arr.push("<div><span>CPU型号</span>&nbsp&nbsp&nbsp&nbsp" + "<span style='float:right'>" + content[2] + "</span></div>")
            arr.push("<div><span>CPU个数</span>&nbsp&nbsp&nbsp&nbsp" + "<span style='float:right'>" + content[3] + "</span></div>")
            arr.push("<div><span>CPU核数</span>&nbsp&nbsp&nbsp&nbsp" + "<span style='float:right'>" + content[4] + "</span></div>")
            arr.push("<div><span>内存</span>&nbsp&nbsp&nbsp&nbsp" + "<span style='float:right'>" + content[5] + " M</span></div>")
            arr.push("<div><span>硬盘</span>&nbsp&nbsp&nbsp&nbsp" + "<span style='float:right'>" + content[6] + "</span></div>")
            arr.push("<div><span>最大文件打开数</span>&nbsp&nbsp&nbsp&nbsp" + "<span style='float:right'>" + content[7] + "</span></div>")
            arr.push("<div><span>运行时间</span>&nbsp&nbsp&nbsp&nbsp" + "<span style='float:right'>" + content[8] + " 天</span></div>")
            arr.push("<div><span>外网IP</span>&nbsp&nbsp&nbsp&nbsp" + "<span style='float:right'>" + content[9] + "</span></div>")
            new_cont = arr.join('');
            tips($(this), new_cont, 'auto', 'auto', 1);
        });

        /*
       *小tips,鼠标悬停提示
       */
        function tips(element, content, width, height, direction, colour) {
            height = height || 'auto';
            width = width || 'auto';
            direction = direction || 1;//提示层默认在上方出现
            colour = colour || '#3595CC';
            element.hover(
                function tips() {
                    index = layer.tips(content, element, {
                        tips: [direction, colour],
                        time: 100000000000,
                        area: [width, height]
                    });
                },
                function () {
                    layer.closeAll('tips');
                }
            );
        }

        /*
*更新机器信息
*/
        $("table tbody tr td a[id^='server_update']").click(function () {
            var id_val = $(this).attr('id'); //获取更新按钮id值
            var id = id_val.split('_')[2]; //获取id值的最后一位
            var data = {"id": id};
            data = JSON.stringify(data);
            var url = "/cmdb/postmachineinfo/";

            $.get(url, {data: data}, function (msg) {
                ajax_callback(msg);
            });
        });


        /*
        *删除机器信息
        */
        $("table tbody tr td a[id^='server_delete']").click(function () {
            var id_val = $(this).attr('id');
            var id = id_val.split('_')[2];
            var data = {"id": id};
            data = JSON.stringify(data);
            var url = "/cmdb/server_delete/";

            var index = layer.confirm('确定删除吗？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                $.post(url, {data: data}, function (msg) {
                    ajax_callback(msg);
                });
            }, function () {
                layer.close(index)
            });
        });


        /*
        *保存编辑服务器信息数据
        */
        $('#editSave').click(function () {
            var server_id = $("#server_id").val();
            var in_ip = $("#in_ip").val();
            var ex_ip = $("#ex_ip").val();
            {#            var project_name = $("#project_name").val();#}
            {#            var service_name = $("#service_name").val();#}
            var groups = $("#edit_groups").val();
            var idc = $("#edit_idc").find("option:selected").val();
            var app = $("#edit_app").find("option:selected").val();
            var user = $("#edit_system_user").find("option:selected").val();
            data = {
                {#                "project_name": project_name,#}
                {#                "service_name": service_name,#}
                "in_ip": in_ip,
                "ex_ip": ex_ip,
                "groups": groups,
                "idc": idc,
                "app": app,
                "user": user,
                "id": server_id
            };
            data = JSON.stringify(data);
            var url = "/cmdb/server_edit/";

            $.post(url, {data: data}, function (msg) {
                $('#editInfoModal').modal('hide')
                ajax_callback(msg);
            });
        });

        /*
        *ajax get callback
        */
        function ajax_callback(msg) {
            var msg = $.parseJSON(msg);
            var index = layer.alert(msg, { //layer控件提示信息
                skin: 'layui-layer-molv' //样式类名
            }, function () {
                if (msg == '刷新成功') {
                    window.location = "/cmdb/server_list/";
                } else if (msg == '批量刷新成功') {
                    window.location = "/cmdb/server_list/";
                } else if (msg == '失败') {
                    window.location = "/cmdb/server_list/";
                }
                    {#        else if (msg == '无权限操作'){#}
                    {#            window.location="/cmdb/server_list/";#}
                    {#        }#}
                else {
                    layer.close(index)
                }
            });
        }

        {#        $('#reset').click(function reset() {#}
        {#            $('#add_ProjectName').val("");#}
        {#            $('#add_ServiceName').val("");#}
        {#            $('#add_InIp').val("");#}
        {#            $('#add_ExIp').val("");#}
        {#            $('#add_Path').val("");#}
        {#        });#}


    </script>
    <!-- 实时搜索 -->
    <script type="text/javascript">
        var flag;

        function func1() {
            clearTimeout(flag);
            flag = setTimeout(function () {
                data();
            }, 200);

        }

        function data() {
            search = $('#search').val();
            $.ajax({
                url: '{% url 'server_search' %}',
                type: 'GET',
                dataType: 'html',
                data: {"search": search},
                success: function (data) {
                    $("#content").html(data);
                }
            });
        }

        $("#search").keyup(function (event) {
            func1();
        });
    </script>
    <!-- 实时搜索End -->


    <script type="text/javascript">
        function reset() {
            $('#email').val("");
        }

        String.prototype.bool = function () {
            return (/^true$/i).test(this);
        };
    </script>

    {#    <script type="text/javascript">#}
    {##}
    {#        $('.btn-email').on('click', function (event) {#}
    {#            var btn = $(event.target);#}
    {#            var row = btn.data('row').split('|');#}
    {#            var id = row[0];#}
    {#            var cauthor = row[1];#}
    {#            var nuser = "{{ request.session.fullname }}";#}
    {#            if (cauthor == nuser || "{{ request.user.is_superuser }}".bool()) {#}
    {#                $("a").attr("data-target", "#editor");#}
    {#                $("#email").empty();#}
    {#                $.get("{% url 'get_email' %}", function (data, status) {#}
    {#                    if (data.length > 0 && status == "success") {#}
    {#                        $.each(jQuery.parseJSON(data), function (k, v) {#}
    {#                            var obj = document.getElementById("email");#}
    {#                            var op = new Option(v.name, v.name)#}
    {#                            obj.add(op);#}
    {#                        })#}
    {#                    }#}
    {#                    resetChosen();#}
    {##}
    {#                });#}
    {##}
    {#                $('.btn-commit').on('click', function () {#}
    {#                    var email_group = $('#email').val();#}
    {#                    $.ajax({#}
    {#                        type: "POST",#}
    {#                        url: "{% url 'send_mails' %}",#}
    {#                        async: true,#}
    {#                        data: {"content_id": id, "email_group": JSON.stringify(email_group)},#}
    {#                        success: function (data, textStatus) {#}
    {#                            window.location.reload()#}
    {#                        },#}
    {#                        error: function (XMLHttpRequest, textStatus, errorThrown) {#}
    {#                            alert(XMLHttpRequest.status);#}
    {#                            alert(XMLHttpRequest.readyState);#}
    {#                            alert(textStatus);#}
    {#                        },#}
    {#                    });#}
    {#                });#}
    {#            }#}
    {#            else {#}
    {#                $("a").removeAttr("data-target");#}
    {#                alert("只有创建者才可以发送通知！");#}
    {#            }#}
    {##}
    {#        });#}
    {##}
    {#    </script>#}

{% endblock %}